package com.bubblegumproject.ogo.remote.http;

import com.bubblegumproject.ogo.remote.RemoteReactor;
import com.bubblegumproject.ogo.remote.OgoRemoteException;
import com.bubblegumproject.ogo.action.Action;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.IOException;

/**
 * A client that can send actions to a remote {@link com.bubblegumproject.ogo.remote.http.HttpExporter}.
 *
 * @author Azubuko Obele (buko.obele@gmail.com)
 */
public class HttpExporterClient implements RemoteReactor {

    private URL agentUrl;

    private HttpExporterClientProtocol clientProtocol;

    public HttpExporterClient(URL agentUrl, HttpExporterClientProtocol clientProtocol) {
        if (agentUrl == null || clientProtocol == null) throw new IllegalArgumentException("null");
        this.agentUrl = agentUrl;
        this.clientProtocol = clientProtocol;
    }

    public Action react(Action action) {
        if (action == null) throw new IllegalArgumentException("null");
        try {
            HttpURLConnection connection = (HttpURLConnection) agentUrl.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setInstanceFollowRedirects(false);

            clientProtocol.serializeRequest(action, connection);
            connection.getOutputStream().flush();

            // TODO: Check some response codes here. The response may not always be an XML document!
            return clientProtocol.parseResponse(connection);
        } catch (IOException ioe) {
            throw new OgoRemoteException(ioe);
        }
    }
}
